Put Numbers in Ascending Order


Posted by Christy on 2022-04-23

Description: Write a function named sort that accepts an array and return the array in ascending order

Note: Don’t use built-in function sort() and the numbers in the array will not repeat.

Thought:

Find the minimum value first and push it into a new array and delete the minimum value in the original array and so on.

function findMin(arr) {
  let min = arr[0];
  let minIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (min > arr[i]) {
      min = arr[i];
      minIndex = i;
    }
  }
  return minIndex;
}

function sort(arr) {
  let newArr = [];
  let length = arr.length;
  for (let i = 0; i < length; i++) {
    let index = findMin(arr);
    newArr.push(arr[index]);
    arr.splice(index, 1);
  }
  return newArr;
}

console.log(sort([6, 8, 3, 2])); // [2, 3, 6, 8]
console.log(sort([1, 2, 7, 5])); // [1, 2, 5, 7]

Reflection:

The key is to get the index and either delete or push it in an array.










Related Posts

1731. The Number of Employees Which Report to Each Employee

1731. The Number of Employees Which Report to Each Employee

番外篇:陽明山東西大縱走心得

番外篇:陽明山東西大縱走心得

簡明程式解題入門 - 字串篇 III

簡明程式解題入門 - 字串篇 III


Comments